package com.akbar.service.impl;

import com.akbar.entity.SysUser;
import com.akbar.mapper.SysUserMapper;
import com.akbar.security.SecurityUser;
import com.akbar.service.ISysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author akbar
 * @since 2025-07-21
 */
@Slf4j
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    private SysUserMapper userMapper;

    /**
     * 从数据库中获取用户信息
     * @param username 前端传过来的用户名
     * @return 返回自定义封装的SecurityUser对象
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUsername, username);
        SysUser sysUser = userMapper.selectOne(queryWrapper);


        if (sysUser == null) {
            throw new UsernameNotFoundException("登录账号不存在");
        }

        // 查询用户角色列表
        List<String> roles = userMapper.selectRoleByUserId(sysUser.getId());
        List<GrantedAuthority> roleAuthorities  = roles.stream()
                .map(role -> new SimpleGrantedAuthority("ROLE_" + role))
                .collect(Collectors.toList());

        // 查询权限列表
        List<String> permissions = userMapper.getPermissionsByUserId(sysUser.getId());
        List<GrantedAuthority> permissionAuthorities = permissions.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());

        // 合并角色和权限
        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.addAll(roleAuthorities);
        authorities.addAll(permissionAuthorities);

        return SecurityUser.builder()
                .sysUser(sysUser)
                .authorities(authorities)
                .build();
    }
}
